package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.search.dao.ESManagerMapper;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.ESManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class ESManagerServiceImpl implements ESManagerService {

	@Autowired
	ElasticsearchTemplate elasticsearchTemplate;

	@Autowired
	ESManagerMapper esManagerMapper;

	@Autowired
	SkuFeign skuFeign;

	/**
	 * 创建索引库结构
	 */
	@Override
	public void createMappingAndIndex() {
		//创建SkuInfo索引
		elasticsearchTemplate.createIndex(SkuInfo.class);

		//创建SkuInfo映射
		elasticsearchTemplate.putMapping(SkuInfo.class);
	}


	/**
	 * 导入全部数据到ES索引库
	 */
	@Override
	public void importAll() {
		//1、先从数据库中获取所有Sku，即List<Sku2>
		List<Sku> skuList = skuFeign.remoteSearchSkuBySpu("all");
		//判空
		if (skuList == null || skuList.size()<=0){
			throw new RuntimeException("当前没有数据被查询到,无法导入索引库");
		}

		//2、将List<Sku>转为JosnString
		String jsonString = JSON.toJSONString(skuList);

		//3、将JsonString转为List<SkuInfo>
		List<SkuInfo> skuInfoList = JSON.parseArray(jsonString, SkuInfo.class);

		//4、遍历List<SkuInfo>，获取spec字符串，将其转为Map类型，再存入
		for (SkuInfo skuInfo : skuInfoList) {
			String spec = skuInfo.getSpec();
			Map map = JSON.parseObject(spec, Map.class);
			skuInfo.setSpecMap(map);
		}

		//5、保存到索引
		esManagerMapper.saveAll(skuInfoList);
	}

	/**
	 * 根据spuid导入数据到ES索引库
	 * @param spuId 商品id
	 */
	@Override
	public void importDataBySpuId(String spuId) {
		List<Sku> skuList = skuFeign.remoteSearchSkuBySpu(spuId);
		if (skuList==null || skuList.size()<=0){  //这里不要漏掉 skuList.size()<=0
			throw new RuntimeException("没有根据spuId，查到sku集合");
		}

		//将skuList转为String
		String skuString = JSON.toJSONString(skuList);
		//将JSONString转为SkuInfon
		List<SkuInfo> skuInfos = JSON.parseArray(skuString, SkuInfo.class);
		//SkuInfo skuInfo1 = JSON.parseObject(skuString, SkuInfo.class);

		//遍历skuInfos，修改每个spec为map
		for (SkuInfo skuInfo : skuInfos) {
			String spec = skuInfo.getSpec();
			Map specMap = JSONObject.parseObject(spec, Map.class);
			skuInfo.setSpecMap(specMap);
		}

		//传到索引
		esManagerMapper.saveAll(skuInfos);
	}


	//根据spu的id，删除索引库的skuInfo
	@Override
	public void delDataBySpuId(String spuId) {
		//根据spuId，获取对应的skuList
		List<Sku> skuList = skuFeign.remoteSearchSkuBySpu(spuId);

		//判空
		if (skuList==null || skuList.size()<=0){
			throw new RuntimeException("没有查到该sku消息，无法完成删除SkuInfo操作");
		}

		//遍历skuList，完成索引库中，每一个sku的删除
		for (Sku sku : skuList) {
			esManagerMapper.deleteById( Long.parseLong ( sku.getId() ) );
		}
	}


}
